package com.lenovo.smarttraffic.zm_user_module;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.lenovo.smarttraffic.R;
import com.lenovo.smarttraffic.api.GetMyCarApi;
import com.lenovo.smarttraffic.api.GetMyCarPeccancy;
import com.lenovo.smarttraffic.api.GetMyCarPeccancyJsonBean;
import com.lenovo.smarttraffic.api.GetPeccancyTypeApi;
import com.lenovo.smarttraffic.bean.CarInfoBean;
import com.lenovo.smarttraffic.bean.CarPeccancyBean;
import com.lenovo.smarttraffic.bean.PeccancyInfoBean;
import com.lenovo.smarttraffic.bean.PeccancyTypeBean;
import com.lenovo.smarttraffic.database.dao.DaoManager_Peccancy;
import com.lenovo.smarttraffic.database.dao.DaoManager_UserInfo;
import com.lenovo.smarttraffic.database.dao.UserInfoBean;
import com.lenovo.smarttraffic.database.dao.UserInfoBeanDao;
import com.lenovo.smarttraffic.database.dao.UserPeccancyBeanDao;
import com.lenovo.smarttraffic.ui.activity.BaseActivity;
import com.lenovo.smarttraffic.ui.activity.Item1Activity;
import com.lenovo.smarttraffic.ui.adapter.BasePagerAdapter;
import com.lenovo.smarttraffic.ui.fragment.fgBean.DragReturnBean;
import com.lenovo.smarttraffic.ui.fragment.fgBean.JsonBean;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class IllegalActivity extends BaseActivity {

    private TextView ill_tv_pName;
    private TextView ill_tv_pSex;
    private TextView ill_tv_pTell;
    private TextView tv_show_noneCar;
    String TAG = "IllegalActivity";
    private UserInfoBean user;
    private CircleImageView iv_sex;
    private String pcardid;
    private String username;
    private ListView ill_lv_main;
    List<CarInfoBean.ROWSDETAILBean> haveCarList = new ArrayList<>();
    public static List<PeccancyInfoBean> adapterlist = new ArrayList<>();
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    adapterlist = (List<PeccancyInfoBean>) msg.obj;
                    // Log.e(TAG, "handleMessage1: " + adapterlist.size());
                    break;
                case 2:
                    DaoManager_Peccancy.getmInstance_Peccancy().init(IllegalActivity.this);
                    UserPeccancyBeanDao dao = DaoManager_Peccancy.getmInstance_Peccancy().getDaoSession_Peccancy().getUserPeccancyBeanDao();
                    List<UserPeccancyBean> list = dao.queryBuilder().where(UserPeccancyBeanDao.Properties.Username.eq(username)).list();
                    if (list.size() == 0) {
                        //  Log.e(TAG, "handleMessage2: " + adapterlist.size());
                        List<PeccancyTypeBean.ROWSDETAILBean> rows_detail = (List<PeccancyTypeBean.ROWSDETAILBean>) msg.obj;
                        for (int i = 0; i < adapterlist.size(); i++) {
                            for (int j = 0; j < rows_detail.size(); j++) {
                                if (adapterlist.get(i).getPremarks().equals(rows_detail.get(j).getPcode())) {
                                    adapterlist.get(i).setPremarks(rows_detail.get(j).getPremarks() + "=");
                                    adapterlist.get(i).setPscore(rows_detail.get(j).getPscore());
                                    adapterlist.get(i).setPmoney(rows_detail.get(j).getPmoney());
                                    dao.insert(new UserPeccancyBean(null, username, adapterlist.get(i).getCarbrand(), adapterlist.get(i).getCarnumber(), adapterlist.get(i).getPaddr(), adapterlist.get(i).getPremarks(), adapterlist.get(i).getPscore(), adapterlist.get(i).getPmoney(), adapterlist.get(i).getPdatetime(), false));
                                }
                            }

                        }
                    }

                    Log.e(TAG, "dao.size = " + dao.queryBuilder().list().size());
                    if (adapterlist.size() == 0) {
                        tv_show_noneCar.setText("恭喜你，暂无违章数据");
                        tv_show_noneCar.setVisibility(View.VISIBLE);
                        ill_lv_main.setVisibility(View.GONE);
                    } else {
                        List<UserPeccancyBean> mylist = dao.queryBuilder().where(UserPeccancyBeanDao.Properties.Username.eq(username)).list();
                        ZmPeccancyItemAdapter zmPeccancyItemAdapter = new ZmPeccancyItemAdapter(IllegalActivity.this, mylist);
                        ill_lv_main.setAdapter(zmPeccancyItemAdapter);
                    }

                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();
        initView();
    }

    private void initData() {
        Intent intent = getIntent();
        username = intent.getStringExtra("username");

        findMyCar();


    }

    //GetCarInfo   api接口中       找到  用户有几个车
    //用 身份证  找   车
    //http://192.168.1.110:8088/transportservice/action/GetCarInfo.do
    private void findMyCar() {
        DaoManager_UserInfo.getmInstance_UserInfo().init(this);
        UserInfoBeanDao userInfoBeanDao = DaoManager_UserInfo.getmInstance_UserInfo().getDaoSession_UserInfo().getUserInfoBeanDao();
        user = userInfoBeanDao.queryBuilder().where(UserInfoBeanDao.Properties.Username.eq(username)).unique();
        pcardid = user.getPcardid();
        adapterlist.clear();


        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://192.168.1.110:8088/transportservice/action/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        GetMyCarApi getMyCarApi = retrofit.create(GetMyCarApi.class);
        Call<CarInfoBean> call1 = getMyCarApi.getCall(new JsonBean("user1"));
        call1.enqueue(new Callback<CarInfoBean>() {
            @Override
            public void onResponse(Call<CarInfoBean> call, Response<CarInfoBean> response) {
                CarInfoBean body = response.body();
                List<CarInfoBean.ROWSDETAILBean> beanList1 = body.getROWS_DETAIL();
                for (int i = 0; i < beanList1.size(); i++) {
                    // 结合数据库   用户名找到身份证
                    // 再用身份证   找车
                    if (pcardid.equals(beanList1.get(i).getPcardid())) {
                        haveCarList.add(beanList1.get(i));
                        MyCarPeccancy(beanList1.get(i));
                    }
                }
                findPCode();
                if (haveCarList.size() == 0) {
                    Log.e(TAG, "该用户无车辆信息  ");
                    tv_show_noneCar.setText("该用户无车辆信息");
                    tv_show_noneCar.setVisibility(View.VISIBLE);
                    ill_lv_main.setVisibility(View.GONE);
                }

            }

            @Override
            public void onFailure(Call<CarInfoBean> call, Throwable t) {
            }
        });
    }


    //那辆车   有什么类型的违章
    //对提交参数敏感  不能随意  因为
    //首先  用户可能有多个车   有可能没有车   每个车  都要调用此方法   且在findMyCar（）方法中调用
    //所以  1.用户没有这个车
    //      2.这个车没有违章记录
    //      服务器都会返回500
    // http://192.168.1.110:8088/transportservice/action/GetCarPeccancy.do
    private void MyCarPeccancy(CarInfoBean.ROWSDETAILBean bean) {
        CarInfoBean.ROWSDETAILBean bean1;
        bean1 = bean;
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://192.168.1.110:8088/transportservice/action/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        GetMyCarPeccancy getMyCarPeccancy = retrofit.create(GetMyCarPeccancy.class);
        Call<CarPeccancyBean> call = getMyCarPeccancy.getCall(new GetMyCarPeccancyJsonBean(username, bean.getCarnumber()));
        call.enqueue(new Callback<CarPeccancyBean>() {
            @Override
            public void onResponse(Call<CarPeccancyBean> call, Response<CarPeccancyBean> response) {
                if (response.isSuccessful()) {
                    CarPeccancyBean body = response.body();
                    List<CarPeccancyBean.ROWSDETAILBean> beans = body.getROWS_DETAIL();
                    int code = response.code();
                    // Log.e(TAG, "onResponse:    sum= " + beans.size() + "==" + code);
                    //违章代码  是什么  意思
                    for (int i = 0; i < beans.size(); i++) {

                        //     Log.e(TAG, "onResponse: " + beans.get(i).toString());
                        adapterlist.add(new PeccancyInfoBean(bean1.getCarbrand(), bean1.getCarnumber(), beans.get(i).getPaddr(), beans.get(i).getPcode(), 0, 0, beans.get(i).getPdatetime()));
                        Message message1 = new Message();
                        message1.what = 1;
                        message1.obj = adapterlist;
                        handler.sendMessage(message1);
                    }
                }

            }

            @Override
            public void onFailure(Call<CarPeccancyBean> call, Throwable t) {

            }
        });
    }


    //  什么样的违章类型    pcode     比如这玩意    1001A  是什么
    //http://192.168.1.110:8088/transportservice/action/GetPeccancyType.do
    private void findPCode() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://192.168.1.110:8088/transportservice/action/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        GetPeccancyTypeApi getPeccancyTypeApi = retrofit.create(GetPeccancyTypeApi.class);
        Call<PeccancyTypeBean> call = getPeccancyTypeApi.getCall(new JsonBean("user1"));
        call.enqueue(new Callback<PeccancyTypeBean>() {
            @Override
            public void onResponse(Call<PeccancyTypeBean> call, Response<PeccancyTypeBean> response) {
                List<PeccancyTypeBean.ROWSDETAILBean> rows_detail = response.body().getROWS_DETAIL();
                Message message = new Message();
                message.what = 2;
                message.obj = rows_detail;
                handler.sendMessage(message);
            }

            @Override
            public void onFailure(Call<PeccancyTypeBean> call, Throwable t) {

            }
        });


    }


    private void initView() {
        initToolBar(findViewById(R.id.toolbar), true, "违章详情");
        ill_tv_pName = (TextView) findViewById(R.id.ill_tv_pName);
        ill_tv_pSex = (TextView) findViewById(R.id.ill_tv_pSex);
        ill_tv_pTell = (TextView) findViewById(R.id.ill_tv_pTell);
        iv_sex = (CircleImageView) findViewById(R.id.iv_sex);
        tv_show_noneCar = (TextView) findViewById(R.id.tv_show_noneCar);
        if (user.getPsex().equals("男")) {
            iv_sex.setImageResource(R.mipmap.touxiang_2);
        } else {
            iv_sex.setImageResource(R.mipmap.touxiang_1);
        }
        ill_tv_pName.setText("姓名：" + user.getPname());
        ill_tv_pSex.setText("性别：" + user.getPsex());
        ill_tv_pTell.setText("手机号码：\n" + user.getPtel());
        ill_lv_main = (ListView) findViewById(R.id.ill_lv_main);
        EventBus.getDefault().register(IllegalActivity.this);
    }


    @Override
    protected int getLayout() {
        return R.layout.activity_illegal;
    }

    //界面排序
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void hanlderMoney(List<UserPeccancyBean> list) {
        ZmPeccancyItemAdapter adapter = new ZmPeccancyItemAdapter(this, list);
        ill_lv_main.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(IllegalActivity.this);
    }

}
